<template>
  <div>
    <table border="1" width="700" style="border-collapse: collapse">
      <caption>
        购物车
      </caption>
      <thead>
        <div>
          <tr>
            <th><input v-model="isAll" type="checkbox" /> <span>全选</span></th>
            <th>名称</th>
            <th>价格</th>
            <th>数量</th>
            <th>总价</th>
            <th>操作</th>
          </tr>
        </div>
      </thead>
      <tbody>
        <Tr :list="goodList"
         @sub="subFun"
         @add="addFun"
         @del="delFun"
        > </Tr>
      </tbody>
      <tfoot>
        <tr>
          <td>合计:{{ sum }}</td>
          <td colspan="5"></td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
import Tr from "./components/Tr.vue";
export default {
  data() {
    return {
      goodList: [
        {
          name: "诸葛亮",
          price: 1000,
          num: 1,
          checked: false,
        },
        {
          name: "蔡文姬",
          price: 1500,
          num: 1,
          checked: false,
        },
        {
          name: "妲己",
          price: 2000,
          num: 1,
          checked: false,
        },
        {
          name: "鲁班",
          price: 2200,
          num: 1,
          checked: false,
        },
      ],
     
    };
  },
  components: {
    Tr,
  },
  computed: {
    isAll: {
      set(val) {
        // console.log(val);
        
       this.goodList.forEach(item => item.checked = val) 
      },
      get() {
        
        return this.goodList.length > 0 && this.goodList.every((item) => item.checked )
      },
    },
   sum(){
     return this.goodList.reduce((prev,item) => prev + item.price * item.num,0)
   }
  },
  methods:{
    subFun(index,b){
      if(this.goodList[index].num > 1) {
         this.goodList[index].num = this.goodList[index].num - b
      }
    },
    addFun(index,a){
     this.goodList[index].num = this.goodList[index].num + a
    },
    delFun(index){
      this.goodList.splice(index, 1)
      
    }
  },
  
};
</script>

<style scoped>
th {
  width: 700px;
  border: 1px solid #000;
}
</style>
